<?php

namespace App\Http\Controllers\Api\Web\Index;

use App\Http\Controllers\Common\ApiController;
use App\Models\Advert\Advert;
use App\Models\Constant\Constant;
use App\Models\Constant\UploadConstant;
use App\Models\School\School;
use App\Models\Site\Setting;
use App\Service\IndexService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Intervention\Image\Facades\Image;

class IndexController extends ApiController {

    private $service;

    public function __construct() {
        $this->service = new IndexService();
    }

    public function index(Request $request) {

        $collegePage = $request->input('collegePage',100);

        $map_type = [
            ['value'=>0,'label'=>'全部'],
            ['value'=>-1,'label'=>'首页'],
            ['value'=>-2,'label'=>'语言中心'],
            ['value'=>-3,'label'=>'留学服务'],
            ['value'=>-4,'label'=>'免考留学'],
            ['value'=>-5,'label'=>'关于我们'],
        ];
        $schools = School::where('status',1)->get(['id as value','name as label']);
        foreach ($schools as $school) {
            $map_type[] = ['value'=>$school->value,'label'=>$school->label];
        }

        $type = array_search('首页',UploadConstant::MAP_ADVERT_TYPE);
        $top_banner = $this->service->getBanner($type);

        $college = $this->service->getCollegeBanner($collegePage);

        //$school = $this->service->getSchoolWithTemplateContent();

        DB::table('site_scan_count')->where('date', date('Y-m-d'))->increment('count');

        return responseSuccess(compact('map_type','top_banner','college'));

    }

    public function ask(Request $request) {

        $this->validate($request, [
            'name'=>'required',
            'phone'=>'required|regex:/^1[3456789]\d{9}$/',
            'wx'=>'required',
        ],[
            'phone.regex'=>'手机不合法',
        ]);

        $name = $request->input('name');
        $phone = $request->input('phone');
        $wx = $request->input('wx');

        $this->service->ask($name, $phone, $wx);

        return responseSuccess();
    }

    public function upload(Request $request){
        $file = $request->file('file');
        $count = $request->input('count',0);
        if(empty($file) || !$file->isValid()){
            return responseFail('文件无效！');
        }
        $size =  $file->getSize();
        $ext = $file->getClientOriginalExtension();
        $origin_name = $file->getClientOriginalName();
        $module = $request->input('module','default');

        //检查目录
        $middlePath = "/$module/".date('Y-m-d');
        $absDir = Storage::disk('upload')->path($middlePath);
        if(!is_dir($absDir)){mkdir($absDir,0777,true);}

        //重命名
        $fileName = time().uniqid().".$ext";

        //如果是图片
        if(in_array($ext, ['jpeg','jpg','bmp','png'])){

            if($request->has('w')){
                $w = $request->input('w');
                $h = $request->input('h');
                if(!empty($w) && !empty($h)){
                    $this->validate($request, [
                        'file' => 'mimes:jpeg,bmp,png,gif|dimensions:width='.$w.',height='.$h,
                    ],[],['w'=>'宽', 'h'=>'高',]);
                }
            }

            $imgIsCut = $request->input('imgIsCut',env('IMG_IS_CUT',false));//是否需要压缩
            $imgIsCutSize = $request->input('imgIsCutSize',env('IMG_IS_CUT_SIZE',1024*1024*1));//压缩阈值
            $imgCutRatio = $request->input('imgCutRatio',env('IMG_CUT_RATION',700));//压缩比

            //如果需要压缩
            if($imgIsCut && $size>=$imgIsCutSize){
                $fileName = time().uniqid().'.jpg';
                $rs = Image::make($file->getRealPath())->resize($imgCutRatio, $imgCutRatio, function ($constraint) {
                    $constraint->aspectRatio();
                })->save($absDir."/$fileName");
                if($rs === false){
                    return responseFail('图片压缩失败');
                }
                $filePath = "$middlePath/$fileName";
            }else{
                $filePath = $file->storeAs($middlePath,$fileName,'upload');
            }
        }
        //如果是文件
        else{
            $filePath = $file->storeAs($middlePath,$fileName,'upload');
        }

        $filePath = Str::replace('//', '/', '/storage/upload/'.$filePath);
        $url = asset($filePath);

        return responseSuccess(compact('filePath','count','size','url','origin_name'));
    }

    public function advert(Request $request){

        $type = $request->input('type','all');
        $status = $request->input('status',1);
        $pageSize = $request->input('pageSize',100);
        $page  = $request->input('page',1);
        $conditions = compact('type','status');

        $conditions['orderBy']['col'] = 'sort';
        $conditions['orderBy']['sort'] = 'desc';

        $records = (new Advert())->getLst($conditions)
            ->orderBy('is_top')
            ->orderByDesc('id')
            ->paginate($pageSize,$this->getCol,'page',$page);

        /*$records = Advert::where('status',1)
            ->orderByDesc('sort')
            ->orderBy('is_top')
            ->orderByDesc('id')
            ->paginate($pageSize,$this->getCol,'page',$page);*/
        /*foreach ($records as $record) {
            $record->type = UploadConstant::MAP_ADVERT_TYPE[$record->type]??'未知';
            $record->pic_url = asset($record->pic_url);
            $record->link = Str::limit($record->link,50);
        }*/
        $mapType = [];
        foreach (UploadConstant::MAP_ADVERT_TYPE as $value=>$label) {
            $mapType[] = compact('value','label');
        }
        return responseSuccess($records->items(),$records->total(),100000,compact('mapType'));

    }

    public function siteInfo(Request $request){
        $records = Setting::get();
        return responseSuccess($records->toArray(),$records->count());
    }

}
